/**
 * Copyright (C) 2016 The yuhaiyang Android Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hitools.template

import android.content.Intent
import android.net.Uri
import android.net.http.SslError
import android.os.Bundle
import android.util.Log
import android.webkit.SslErrorHandler
import android.webkit.WebResourceError
import android.webkit.WebResourceRequest
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import com.hitools.template.utils.WebViewUtils

/**
 * 只有一个Webview的 Activity
 */
open class BaseWebActivity : AppCompatActivity() {
    private var isError: Boolean = false
    private lateinit var webView: WebView
    private lateinit var url: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getLayout())
        initViews()
    }

    private fun initViews() {
        url = getUrl()
        webView = findViewById(R.id.webView)
        initWebView()
        webView.webViewClient = getWebViewClient()
        webView.loadUrl(url)

        webView.setDownloadListener { url, _, _, _, _ ->
            val intent = Intent(Intent.ACTION_VIEW)
            intent.addCategory(Intent.CATEGORY_BROWSABLE)
            intent.data = Uri.parse(url)
            startActivity(intent)
        }
    }


    /**
     * 获取当前的Url
     */
    open fun getUrl() = "https://www.baidu.com/"

    /**
     * 获取当前的Layout
     */
    open fun getLayout() = R.layout.activity_base_only_web

    /**
     * 初始化
     */
    open fun initWebView() {
        WebViewUtils.init(webView)
    }


    open fun getWebViewClient(): WebViewClient {
        return WebClient()
    }

    override fun onResume() {
        super.onResume()
        webView.onResume()
    }

    override fun onPause() {
        super.onPause()
        webView.onPause()
    }


    open fun showError() {

    }


    override fun onBackPressed() {
        Log.i(TAG, "onBackPressed: ")
        if (webView.canGoBack() && !isError) {
            webView.goBack()
        } else {
            Log.i(TAG, "onBackPressed: 2")
            super.onBackPressed()
        }
    }


    private inner class WebClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
            Log.i("yhy", "shouldOverrideUrlLoading: url = ${request.url}")
            view.loadUrl(request.url.toString())
            return true;
        }

        override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
            super.onReceivedError(view, request, error)
            if (request == null || !request.isForMainFrame) {
                return
            }
            isError = true
            showError()
        }

        override fun onReceivedHttpError(view: WebView?, request: WebResourceRequest?, errorResponse: WebResourceResponse?) {
            super.onReceivedHttpError(view, request, errorResponse)
            if (request == null || !request.isForMainFrame) {
                return
            }
            isError = true
            showError()
        }

        override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
            super.onReceivedSslError(view, handler, error)
            handler?.proceed()
        }
    }

    companion object {
        private const val TAG = "BaseWebActivity"
    }
}
